<template>
  <div class="search-suggestion">
    <van-cell 
    v-for="(item,index) in list" 
    @click="$emit('updateSearchText',item)"
    :key="index" 
    icon="search">
    <div v-html="hightlight(item)"></div>
    </van-cell>
  </div>
</template>

<script>
import { getSearchSuggestion } from "@/api/search";
import { debounce } from "lodash"
export default {
  name: "SearchSuggestion",
  components: {},
  props: {
    // 搜索父组件的内容
    searchText: {
      type: String,
      required: true
    }
  },
  data() {
    return {
      list: []
    };
  },
  computed: {},
  watch: {
    // 监听输入内容变化
    searchText: {
      // handler(newval) {
      //   this.loadSuggestion(newval)
      // },
      // 防抖lodash引用
      handler:debounce(function(newval){
        this.loadSuggestion(newval)

      },1000),
      immediate: true // 第一次就要执行
    }
  },
  created() {},
  mounted() {},
  methods: {
    async loadSuggestion (v){
      try {
        const { data:res } = await getSearchSuggestion(v)
        this.list = res.data.options
      } catch (error) {
        this.$toast.fail('获取联想数据失败')
      }
    },
    hightlight(val){
      // console.log(val);
      // 设置正则，忽略大小写全局匹配
      let reg = new RegExp(this.searchText,'gi')
      // 关键字变成带span的搜索关键字替换
      let newStr = val.replace(reg,`<span style="color:yellow">${this.searchText}</span>`)
      // 返回值
      return newStr
    }
  }
};
</script>

<style scoped lang="less"></style>
